﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using CSharpTest.Net.Crypto;
using System.Security.Cryptography;
using System.Xml;
using System.IO;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;

namespace SmartVault.Core
{
    /// <summary>
    /// RSAPrivateKey2
    /// 
    /// Extends RSAPrivateKey to introduce the ability to work with PEM files.
    ///
    /// This functionality should be ported back into CSharpTest.Net
    /// </summary>
    public class RSAPrivateKey2 : RSAPrivateKey
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="provider"></param>
        public RSAPrivateKey2(RSACryptoServiceProvider provider)
            : base(provider)
        {

        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="parameters"></param>
        public RSAPrivateKey2(RSAParameters parameters)
            : base(parameters)
        {

        }

        /// <summary>
        /// FromXml
        /// </summary>
        /// <param name="xrdr"></param>
        /// <returns></returns>
        public new static RSAPrivateKey2 FromXml(XmlReader xrdr)
        {

            RSAParameters param = new RSAParameters();
            while (xrdr.Read())
            {
                if (xrdr.NodeType == XmlNodeType.Element)
                {
                    if (xrdr.LocalName == "Modulus") param.Modulus = Convert.FromBase64String(xrdr.ReadElementString());
                    if (xrdr.LocalName == "Exponent") param.Exponent = Convert.FromBase64String(xrdr.ReadElementString());
                    if (xrdr.LocalName == "P") param.P = Convert.FromBase64String(xrdr.ReadElementString());
                    if (xrdr.LocalName == "Q") param.Q = Convert.FromBase64String(xrdr.ReadElementString());
                    if (xrdr.LocalName == "DP") param.DP = Convert.FromBase64String(xrdr.ReadElementString());
                    if (xrdr.LocalName == "DQ") param.DQ = Convert.FromBase64String(xrdr.ReadElementString());
                    if (xrdr.LocalName == "InverseQ") param.InverseQ = Convert.FromBase64String(xrdr.ReadElementString());
                    if (xrdr.LocalName == "D") param.D = Convert.FromBase64String(xrdr.ReadElementString());
                }
            }
            Check.Assert<FormatException>(param.Modulus != null && param.Exponent != null
                 && param.P != null && param.Q != null && param.DP != null
                 && param.DQ != null && param.InverseQ != null && param.D != null);
            return new RSAPrivateKey2(param);
        }

        /// <summary>
        /// Writes the private key to PEM format
        /// </summary>
        /// <param name="writer"></param>
        public void WritePEM(TextWriter writer)
        {
            var x = new PemWriter(writer);

            var y = this.ExportParameters();

            var z = new RsaPrivateCrtKeyParameters
                (
                new BigInteger(1, y.Modulus),       /* modolus */
                new BigInteger(1, y.Exponent),      /* public exponent */
                new BigInteger(1, y.D),              /* private exponent */
                new BigInteger(1, y.P),             /* p */
                new BigInteger(1, y.Q),             /* q */
                new BigInteger(1, y.DP),            /* dp */
                new BigInteger(1, y.DQ),            /* dq */
                new BigInteger(1, y.InverseQ)       /* qInv */
                );                      

            x.WriteObject(z);
        }

        /// <summary>
        /// Convert the private key to PEM format
        /// </summary>
        /// <returns></returns>
        public string ToPEM()
        {
            using (StringWriter str = new StringWriter())
            {
                WritePEM(str);
                return str.ToString();
            }
        }
    }
}
